import { get as getVal, writable, type Writable } from "svelte/store";
import { object, string, number } from "yup";
import type { Paged } from "@util/http";

export type DatasetAnnotation = {
  id: number;
  updated_at: string | null;
  dataset_id: number;
  entry_id: number;
  label: string | null;
  text_annotations: any | null;
  vote_cnt: number;
};

export type ExDatasetAnnotation = DatasetAnnotation & {
  my_annotation_flag: boolean;
};

export type ListDatasetAnnotationsParam = {
  dataset_entry_id: number;
  page_no?: number;
  page_size?: number;
};


export type CreateDatasetAnnotationParam = {
  dataset_id: number;
  entry_id: number;
  label: string | null;
  text_annotations?: any;
};

export type UpdateDatasetAnnotationParam = {
  id: number;
  label: string | null;
  text_annotations?: any | null;
};

export type DeleteDatasetAnnotationParam = {
  id: number;
};


export const DatasetAnnotationSchema = object({
  id: number().required("数据项标注id必填"),
  updated_at: string().optional(),
  dataset_id: number().required("数据集id必填"),
  entry_id: number().required("数据项id必填"),
  label: string().optional().max(128, "最多128个字"),
  vote_cnt: number(),
});

export const CreateDatasetAnnotationParamSchema = DatasetAnnotationSchema.omit(["id", "updated_at", "vote_cnt"]);


export const DatasetAnnotationFactory = (dataset_id: number, entry_id: number, label?: string, text_annotations?: any) => {
  return (): DatasetAnnotation =>  ({ id: null, updated_at:null, dataset_id, entry_id, label, text_annotations, vote_cnt: 0 })
}

type DatasetAnnotationMap = {
  [k: number]: Writable<Paged<ExDatasetAnnotation>>;
};

const datasetAnnotationMap: DatasetAnnotationMap = {};

export const setDatasetAnnotationSubscribe = (entry_id: number, o: Paged<ExDatasetAnnotation>) => {
  if (!datasetAnnotationMap[entry_id]) {
    datasetAnnotationMap[entry_id] = writable(o);
  }
  datasetAnnotationMap[entry_id].set(o);
};

export const getDatasetAnnotationSubscribe = (entry_id: number) => {
  let v = datasetAnnotationMap[entry_id];
  if (!v) {
    datasetAnnotationMap[entry_id] = v = writable();
  }
  return v;
};

export const hasDatasetAnnotationSubscribe = (entry_id: number) => {
  return datasetAnnotationMap[entry_id] && getVal(datasetAnnotationMap[entry_id]) !== undefined;
};